package com.yt.user.service;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.yt.user.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.user.mapper.AccountInfoMapper;
import com.yt.user.models.service.IAccountInfoService;
import com.yt.user.models.bo.AccountInfoSaveBO;
import com.yt.user.models.dto.AccountInfoDTO;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 账号信息控制器
 *
 * @author yzz
 * @Date 2025-10-22 09:37:39
 */
@DubboService
public class AccountInfoServiceImpl extends ServiceImpl<AccountInfoMapper, AccountInfoDTO> implements IAccountInfoService{

    @Resource
    private YmlConfig ymlConfig;
    
    // 用于同一毫秒内生成不同的ID
    private final AtomicLong sequence = new AtomicLong(0);
    // 上次生成ID的时间戳
    private volatile long lastTimestamp = 0;

    @Override
    public boolean add(AccountInfoSaveBO saveBO) {
        AccountInfoDTO dto = new AccountInfoDTO();
        
        // 手动复制字段，确保所有字段都被正确设置
        if (saveBO.getId() != null && !saveBO.getId().isEmpty()) {
            dto.setId(saveBO.getId());
        } else {
            // 使用自定义ID生成策略
            dto.setId(generateAccountId(saveBO.getPhone()));
        }
        
        dto.setPreDeposit(saveBO.getPreDeposit());
        dto.setTotalConsumption(saveBO.getTotalConsumption());
        // 修复字段名拼写错误：monthConsuption -> monthConsumption
        dto.setMonthConsumption(saveBO.getMonthConsumption());
        dto.setIsArrears(saveBO.getIsArrears());
        dto.setArrearsAmount(saveBO.getArrearsAmount());
        dto.setPhone(saveBO.getPhone());
        
        // 添加日志输出，方便调试
        System.out.println("准备插入的数据: " + dto);
        
        try {
            // 使用insert方法插入数据，让MyBatis Plus自动填充createTime和updateTime字段
            boolean result = this.insert(dto);
            
            // 添加日志输出，方便调试
            System.out.println("插入结果: " + result);
            return result;
        } catch (Exception e) {
            System.err.println("插入数据时发生异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 生成账号ID
     * 格式：时间戳(13位) + 手机号后4位 + 序列号(3位)
     * @param phone 用户手机号
     * @return 账号ID
     */
    private String generateAccountId(String phone) {
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();
        
        // 确保同一毫秒内的序列号递增
        if (timestamp == lastTimestamp) {
            sequence.incrementAndGet();
        } else {
            sequence.set(0);
            lastTimestamp = timestamp;
        }
        
        // 获取手机号后4位，如果手机号为空则用0000代替
        String phoneSuffix = "0000";
        if (phone != null && phone.length() >= 4) {
            phoneSuffix = phone.substring(phone.length() - 4);
        }
        
        // 格式化序列号为3位数字
        long seq = sequence.get() % 1000;
        String sequenceStr = String.format("%03d", seq);
        
        // 拼接生成最终的accountId
        return timestamp + phoneSuffix + sequenceStr;
    }
    
    @Override
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }
    
    @Override
    public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
        return super.deleteBatchIds(idList);
    }
    
    @Override
    public AccountInfoDTO selectById(Serializable id) {
        return super.selectById(id);
    }
}